package com.mfoyou.agent.web.utils.withdraw;

import org.mfoyou.agent.common.dao.domain.HuawuAlipay;
import org.mfoyou.agent.utils.common.Logger;
import org.mfoyou.agent.utils.common.MfoyouMap;
import org.mfoyou.agent.utils.common.StrUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;

public class AliPayWithDraw extends AbstractWithDraw {

    private static Logger logger = Logger.getLogger(AliPayWithDraw.class);

    private static String getWay = "https://openapi.alipay.com/gateway.do";

    private int extractId;

    private Integer amount;

    private String name;

    private String account;

    private HuawuAlipay huawuAlipay;

    public AliPayWithDraw(int extractId, Integer amount, String name, String account, HuawuAlipay huawuAlipay) {
        super();
        this.extractId = extractId;
        this.amount = amount;
        this.name = name;
        this.account = account;
        this.huawuAlipay = huawuAlipay;
    }

    @Override
    public boolean dealWith() {
        AlipayFundTransToaccountTransferResponse response = extract();
        if (response == null) {
            setMessage("支付宝配置错误");
            return false;
        }
        if (response.isSuccess()) {
            return true;
        }
        JSONObject parseObject = JSON.parseObject(response.getBody());
        setMessage(parseObject.getJSONObject("alipay_fund_trans_toaccount_transfer_response").getString("sub_msg"));
        return false;
    }

    public AlipayFundTransToaccountTransferResponse extract() {
        if (huawuAlipay == null) {
            return null;
        }
        AlipayClient alipayClient = new DefaultAlipayClient(getWay, huawuAlipay.getAlipayAppid(),
                huawuAlipay.getAlipayPrivateKey(), "json", "utf-8", huawuAlipay.getAlipayPublicKey(), "RSA2");
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        MfoyouMap map = new MfoyouMap();
        map.put("out_biz_no", "" + extractId);
        map.put("payee_type", "ALIPAY_LOGONID");
        map.put("payee_account", account);
        map.put("amount", StrUtil.fen2yuan(amount));
        map.put("payer_show_name", "mfoyou提现");
        if (name != null) {
            map.put("payee_real_name", name);
        }
        map.put("remark", "mfoyou提现,加入mfoyou,成就创业梦想");
        request.setBizContent(JSON.toJSONString(map));
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.error(JSON.toJSONString(map), e);
            e.printStackTrace();
        }
        return response;
    }

}
